package ru.gerunn.silent.server;

import java.io.IOException;
import java.util.ArrayList;

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

import ru.gerunn.silent.message.MessageQueue;
import ru.gerunn.silent.message.MessageThread;
import ru.gerunn.silent.trash.User;

public class Server implements Runnable {

	private int port;
	private ArrayList<Session> sessions;
	private MessageQueue messageQueue;

	public Server() {
		this.setPort(8883);
	}

	public Server(int port) {
		this.setPort(port);
	}

	public void run() {
		try {
			System.setProperty("javax.net.ssl.keyStore", "keystore.jks");
			System.setProperty("javax.net.ssl.keyStorePassword", "Hjz3&5");

			SSLServerSocketFactory serverSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
			SSLServerSocket serverSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(this.port);
			SSLSocket socket = null;

			this.setSessions(new ArrayList<Session>());
			this.setMessageQueue(new MessageQueue());

			new Thread(new ServerSession()).start();
			new Thread(new MessageThread(this.getMessageQueue())).start();

			while ((socket = (SSLSocket) serverSocket.accept()) != null) {
				User user = new User();
				Session session = new Session(socket, this, user);
				this.startSession(session);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	private void startSession(Session session) {
		new Thread(session).start();
	}

	public ArrayList<Session> getSessions() {
		return sessions;
	}

	public void setSessions(ArrayList<Session> sessions) {
		this.sessions = sessions;
	}

	public MessageQueue getMessageQueue() {
		return messageQueue;
	}

	private void setMessageQueue(MessageQueue messageQueue) {
		this.messageQueue = messageQueue;
	}

}
